package com.chinairi.mall.util;

import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 解密
 *
 * @author hhm
 * @date 2019年9月9日
 * @version 1.0
 */
public abstract class AbstractEncryptUtil {

    private static final String KEY = "0102030405060708";
    /**
     * 偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
     */
    private static final String IV_CODE = "0102030405060709";
    private static final String ALGORITHM = "AES";
    /**
     * 算法/模式/补码方式
     */
    private static final String ALGORITHM_PROVIDER = "AES/CBC/PKCS5Padding";

    /**
     * 解密
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc) throws Exception {

        try {
            byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_PROVIDER);
            IvParameterSpec iv = new IvParameterSpec(IV_CODE.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            //先用bAES64解密
            byte[] encrypted1 = base64Decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * bAES64解密
     * @param value
     * @return
     * @throws IOException
     */
    private static byte[] base64Decode(String value) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedValue = decoder.decodeBuffer(value);
        return decodedValue;
    }

}
